package com.example.template.interceptor;

import com.example.template.common.annontation.RequiredPermission;
import com.example.template.common.api.ApiCodeConstant;
import com.example.template.common.exception.GlobalException;
import com.example.template.service.PermissionService;
import com.example.template.utils.JsonUtil;
import com.example.template.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @className: PermissionInterceptor
 * @description: 权限拦截器
 * @author: Kuangkeli
 * @date: 2024/01/30 9:27
 **/

@Component
public class PermissionInterceptor implements HandlerInterceptor {
    private static Logger log = LoggerFactory.getLogger(PermissionInterceptor.class);

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JsonUtil jsonUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        System.out.println("权限拦截器被调用");
        long userId = Long.parseLong(String.valueOf(request.getAttribute("userId")));
        // 验证权限
        if (this.hasPermission(handler,userId)) {
            log.info("hasPermission");
            request.setAttribute("userId",userId);
            return true;
        }
        log.info("No Permission");
        throw new GlobalException(ApiCodeConstant.RESULT_PERMISSION_EXCEPTION,"无权限");
    }

    /**
     * 是否有权限 如果方法和类都未标记权限接口 则说明该接口为开放接口未设置权限
     * @param handler
     * @return
     */
    private boolean hasPermission(Object handler,long userId) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法上的注解
            RequiredPermission requiredPermission = handlerMethod.getMethod().getAnnotation(RequiredPermission.class);
            // 如果方法上的注解为空 则获取类的注解
            if (requiredPermission == null) {
                requiredPermission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequiredPermission.class);
            }
            // 如果标记了注解，则判断权限
            if (requiredPermission != null && StringUtils.isNotBlank(requiredPermission.value())) {
                // redis或数据库 中获取该用户的权限信息 并判断是否有权限,优先从redis获取
                List<String> perms = (jsonUtil.parseArray(redisUtil.get("perms:"+userId).toString()));
                if (CollectionUtils.isEmpty(perms) ){
                   return false;
                }
                return perms.contains(requiredPermission.value());
            }
        }
        return true;
    }

}
